<template>
  <section>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item>酒店</el-breadcrumb-item>
      <el-breadcrumb-item
        >{{ $route.query.city ? city : "" }}酒店预订</el-breadcrumb-item
      >
    </el-breadcrumb>

    <!-- 搜索条 -->
    <div ref="searchBarRef">
      <SearchBar @search-event="setSearchQuery" />
    </div>

    <!-- 地区信息 -->
    <AreaInfo :data="hotelList" />

    <!-- 条件筛选 -->
    <div ref="hotelRef">
      <HotelFilter @filter-event="setFilterQuery" />
    </div>

    <!-- 酒店列表 -->
    <div
      class="loading_box"
      :class="loading ? 'loading' : ''"
      v-loading="loading"
      element-loading-spinner="el-icon-loading"
      element-loading-text="拼命加载中"
    ></div>
    <div v-if="hotelList.length === 0 && !loading" class="empty">
      暂无符合条件的酒店
    </div>
    <div v-else class="hotel_list">
      <Hotel
        ref="itemRef"
        :data="item"
        v-for="item in hotelList"
        :key="item.id"
        @over="over"
      />

      <!-- 分页部分 -->
      <div class="pagenation">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page.sync="pageIndex"
          prev-text="上一页"
          next-text="下一页"
          layout="prev, pager, next"
          :total="total"
        ></el-pagination>
      </div>
    </div>

    <!-- <el-backtop></el-backtop> -->
    <ToTop />

    <!-- 固定窗口 -->
    <div id="fixed_box" class="fixedMap" v-if="showFixed"></div>
  </section>
</template>

<script>
import { mapState } from "vuex";
import SearchBar from "@/components/hotel/citySearch";
import Hotel from "@/components/hotel/hotelItem";
import AreaInfo from "@/components/hotel/AreaInfo";
import HotelFilter from "@/components/hotel/filterHotel";

export default {
  data() {
    return {
      // 酒店列表数据
      hotelList: [],
      // 酒店总数
      total: 0,
      // 从几条数据获取
      nextStart: 0,
      // 当前页、
      pageIndex: 1,
      // 搜索请求参数
      searchQuery: {
        // 城市id
        city: "",
        // 入店时间、
        enterTime: "",
        // 离店时间
        leftTime: "",
      },
      //  过滤请求参数
      filterQuery: {
        // 价格
        price: 4000,
        // 住宿等级、
        hotellevel: [],
        // 住宿类型、
        hoteltype: [],
        // 酒店设施、
        assets: [],
        // 酒店品牌、
        brands: [],
      },
      loading: true,
      showFixed: false,
      fixedMap: null,
      markers: [],
    };
  },

  components: {
    SearchBar,
    Hotel,
    AreaInfo,
    HotelFilter,
  },

  methods: {
    // 获取酒店信息
    async getHotelList() {
      let query = `?_start=${this.nextStart}`;

      // 将搜索内容不为空选项添加到请求参数中
      for (const key in this.searchQuery) {
        if (this.searchQuery[key]) {
          query += `&${key}=${this.searchQuery[key]}`;
        }
      }

      // 拼接过滤参数
      if (this.filterQuery.price) {
        query += `&price_lt=${this.filterQuery.price}`;
      }
      if (this.filterQuery.hotellevel.length > 0) {
        this.filterQuery.hotellevel.forEach((item) => {
          query += `&hotellevel_in=${item.id}`;
        });
      }
      if (this.filterQuery.hoteltype.length > 0) {
        this.filterQuery.hoteltype.forEach((item) => {
          query += `&hoteltype_in=${item.id}`;
        });
      }
      if (this.filterQuery.assets.length > 0) {
        this.filterQuery.assets.forEach((item) => {
          query += `&hotelasset_in=${item.id}`;
        });
      }
      if (this.filterQuery.brands.length > 0) {
        this.filterQuery.brands.forEach((item) => {
          query += `&hotelbrand_in=${item.id}`;
        });
      }
      console.log(query);

      // 请求前显示加载
      this.loading = true;
      const { data } = await this.$axios
        .get("/hotels" + query)
        .catch((err) => err.response);
      // console.log(data);
      if (data.statusCode === 500) {
        this.getHotelList();
      } else {
        this.total = data.total;
        this.hotelList = data.data;
        // 关闭加载
        this.loading = false;
      }
    },

    // 当前页码改变事件
    handleCurrentChange(val) {
      this.pageIndex = val;
      this.nextStart = (val - 1) * 10;
      // Element.scrollIntoView() 方法让当前的元素滚动到浏览器窗口的可视区域内。
      this.$refs.searchBarRef.scrollIntoView();
      this.getHotelList();
    },

    // 设置搜索条请求参数
    setSearchQuery(data) {
      console.log("搜索");
      this.searchQuery = data;
      // 重置请求开始的条数
      this.nextStart = 0;
      this.pageIndex = 1;
      // 发送搜索请求
      this.getHotelList();
    },

    // 设置过滤请求参数
    setFilterQuery(data) {
      // console.log('过滤');
      this.filterQuery = data;
      // 重置请求开始的条数
      this.nextStart = 0;
      this.pageIndex = 1;
      this.getHotelList();
    },

    // 页面滚动事件
    // scrollToTop() {
    //   if (!this.$refs.hotelRef) return;
    //   var scrollTop =
    //     window.pageYOffset ||
    //     document.documentElement.scrollTop ||
    //     document.body.scrollTop;
    //   // console.log(this.$refs.hotelRef.offsetTop);
    //   if (scrollTop > this.$refs.hotelRef.offsetTop) {
    //     this.showFixed = true;
    //     if (!this.fixedMap) {
    //       setTimeout(() => {
    //         // 高德地图
    //         this.fixedMap = new AMap.Map("fixed_box", {
    //           // 地图大小
    //           zoom: 20,
    //           // 设置地图刚开始进来的中心点
    //           center: [
    //             this.hotelList[0].location.longitude,
    //             this.hotelList[0].location.latitude,
    //           ],
    //           viewMode: "3D",
    //         });
    //         // 渲染点标记
    //         this.sign();
    //       }, 100);
    //     }
    //   } else {
    //     this.showFixed = false;
    //     this.fixedMap = null;
    //   }
    // },
    // 鼠标移上触发地图响应
    over(hotelId) {
      this.markers.forEach((res) => {
        if (res.getExtData() == hotelId) {
          // 将当前匹配的点置顶
          res.setTop(true);
          //提示内容
          const infoWindow = new AMap.InfoWindow({
            content: `<span style='font-size:12px;color:#333'>${res.getTitle()}</span>`,
            offset: new AMap.Pixel(0, -32),
          });
          infoWindow.open(this.fixedMap, res.getPosition());
          // 将当前的点设置为中心点
          setTimeout(() => {
            this.fixedMap.setCenter(res.getPosition());
          }, 150);
        }
      });
    },
    // 添加多个点标记
    sign() {
      console.log(this.hotelList);
      // 把遍历到的酒店经纬度信息，先遍历添加到每一个点标记，再把多个点标记存到当前数组
      this.markers = this.hotelList.map((res, index) => {
        // 添加单个地图点标记
        var marker = new AMap.Marker({
          // 设置点标记名字
          title: res.name,
          // 点标记的经纬度信息
          position: [res.location.longitude, res.location.latitude],
          // 自定义属性，利用它来存id，实现鼠标移动功能
          extData: res.id,
          // 改变地图小图标的样式
          content: `<div class="mapImg">
                        <img src="https://webapi.amap.com/theme/v1.3/markers/n/mark_bs.png" alt />
                        <span>${index + 1}</span>
                      </div>`,
        });
        // 鼠标在地图移动的时候，触发
        marker.on("mouseover", () => {
          return this.over(res.id);
        });
        return marker;
      });
      // 清理多余的障碍物
      this.fixedMap.clearMap();
      // 添加标记
      this.fixedMap.add(this.markers);
    },
  },

  computed: {
    ...mapState({
      city(state) {
        return state.hotel.city;
      },
    }),
  },

  mounted() {
    window.addEventListener("scroll", this.scrollToTop);
  },

  // created() {
  //   // 挂载数据
  //   this.getHotelList()
  // }
};
</script>

<style lang="less" scoped>
section {
  width: 1000px;
  margin: auto;

  .el-breadcrumb {
    padding: 20px 0;
  }

  .loading_box {
    transition: all 0.5s;

    /deep/.el-icon-loading {
      font-size: 60px;
      font-weight: 700;
      color: #ccc;
    }

    /deep/ .el-loading-text {
      font-size: 18px;
      color: #ccc;
    }
  }
  .loading {
    margin-top: 10px;
    height: 150px;
  }

  .empty {
    margin: 20px 0 40px;
    text-align: center;
  }

  /deep/ .btn-prev,
  /deep/ .btn-next {
    span {
      display: inline-block;
      width: 85px;
      height: 28px;
      line-height: 28px;
      border: 1px solid #ddd;
      border-radius: 4px;
    }

    &:hover:not([disabled="disabled"]) span {
      color: #409eff;
      border-color: #c6e2ff;
      background-color: #ecf5ff;

      &:before,
      &:after {
        color: #409eff;
      }
    }
  }

  /deep/ .btn-prev span {
    &:before {
      content: "<";
      margin-right: 5px;
      font-family: serif;
      font-weight: 700;
      color: #c0c4cc;
    }
  }

  /deep/ .btn-next span {
    &:after {
      content: ">";
      margin-left: 5px;
      font-family: serif;
      font-weight: 700;
      color: #c0c4cc;
    }
  }

  .pagenation {
    margin: 20px 0 40px;
    text-align: right;
  }

  .el-backtop {
    left: 50%;
    bottom: 0;
    transform: translateX(520px);
  }

  .fixedMap {
    position: fixed;
    width: 300px;
    height: 280px;
    top: 30px;
    right: 50%;
    transform: translateX(-550px);
    // background-color: pink;
  }
  /deep/.mapImg {
    position: relative;

    height: 30px;
    img {
      width: 27px;
      object-fit: cover;
    }

    span {
      position: absolute;
      top: -4px;
      left: 3px;
      width: 20px;
      height: 30px;
      text-align: center;
      line-height: 34px;
      color: #fff;
      font-size: 12px;
    }
  }
}
</style>